GBML manual / Maths

dist_sq

The distance between two points MULTIPLIED BY ITSELF, with no square root, so it is quick. Use it to ask "which is closer" or "is it near enough" for lots of things at once: dist_sq(x, y, other.x, other.y) < square_int(32) means "within 32 pixels". The answer is a whole number.

Works differently on Game Boy - A squared distance on the Game Boy stops at 32,767, which is about 181 pixels apart; two points farther apart answer 32,767.

Works differently on Game Boy Color - A squared distance on the Game Boy Color stops at 32,767, which is about 181 pixels apart; two points farther apart answer 32,767.

On other consoles this differs: see Side by side and How the consoles differ.

Syntax

dist_sq(x1, y1, x2, y2) -> int

Arguments

NameType
x1real
y1real
x2real
y2real

Returns

int

Description

The distance between two points multiplied by itself, with no square root. That makes it quick. Use it when you only want to ask "which is closer?" or "is it near enough?", especially for lots of things at once.

Both points count from the top-left, the same as dist_to, and the answer is a whole number.

Example

var near = dist_sq(x, y, 100, 60) < square_int(32);

near is true when the walker is within 32 pixels of the point (100, 60). Squaring the 32 instead of taking a square root of the distance gives the same answer, faster.

To find the closer of two things, compare their dist_sq numbers: the smaller one is closer.

Why the answer is a whole number

A real runs out of room at 524,287, which is only about 724 pixels apart when squared. A whole number holds points 46,000 pixels apart. So dist_sq gives back a whole number, and you compare it with a whole number, such as square_int(32) or 32 * 32.

The small print

Cost

A few multiplies and adds, no square root.

On the GBA

Both points count from the top-left, the same as dist_to. It counts fractions of a pixel in each difference (the same as dist_to) and the answer, rounded down, is a WHOLE number, not a real: a real runs out at 524,287, which is only about 724 pixels apart squared, while a whole number holds points 46,000 pixels apart. Compare it with a whole number (square_int(32), or 32 * 32), not with a real. Two points at the same spot give 0. No square root, so it is much cheaper than dist_to when you only need to compare.

See also: dist_tosquare_intdir_tocollision_circle